package src;

import java.util.LinkedList;

/**
 * Created by IntelliJ IDEA.
 * User: Helgi
 * Date: 25.2.2011
 * Time: 20:07
 * To change this template use File | Settings | File Templates.
 */
public class ClockAlgorithm
{
    public ClockAlgorithm(int memSize, int memString[])
	{
		// The usual initialization.

        ClockBendir=0;
		_pageFaults = 0;
		_memory = new LinkedList();
        refrencebit = new LinkedList();
		_memSize = memSize;
		// Run our experiment
		for (int i = 0; i < memString.length; i++)
			memAccess(memString[i]);
	}

	//
	// memAccess
	//
	// Access a virtual memory page. We count a page fault if the virtual page is not in
	// memory.
	//
	private void memAccess(int page)
	{
		if (!_memory.contains(new Integer(page)))
			pageFault(page);
        else   //if the page is refered again it will change it refrencebit to 1
		{
			for(int i=0; i<_memory.size(); i++)
			{
				if((Integer)_memory.get(i)==page)
                        refrencebit.set(i, 1);
			}
		}
	}

	//
	// pageFault
	//
	// Page fault handling. This is the section of code that you should change in implementing your
	// other page replacement algorithms
	//
	private void pageFault(int page)
	{
		_pageFaults++; // Increment the page fault counter.

        boolean idone = false; //this is so it will look until the page has been entered into _memory

		// Check if there is space in our memory -- free page frames.
        if (_memSize == _memory.size())
        {
            do{
                if((Integer)refrencebit.get(ClockBendir) == 1)
                {
                    refrencebit.set(ClockBendir,0);  //sets the rerencebit to 0

                    ClockBendir++;
                    if(ClockBendir >= _memSize) //ef það er farið í hring
                        ClockBendir=0;
                }

                if((Integer)refrencebit.get(ClockBendir) == 0)
                {
                    idone=true;

                    refrencebit.set(ClockBendir,1);
                    _memory.set(ClockBendir,page);

                    ClockBendir++;
                    if(ClockBendir >= _memSize) //ef það er farið í hring
                        ClockBendir=0;
                }

            }while(!idone);
        }
        else
        {
            _memory.addLast(new Integer(page));
            refrencebit.addLast(1);
        }
	}

	//
	// pageFaults
	//
	// Give the total page faults generated in the experiment
	//
	public int pageFaults()
	{
		return _pageFaults;
	}

    private int ClockBendir;
	private LinkedList _memory;		// The simulated memory
    private LinkedList refrencebit;
	private int _memSize;			// Memory size in page frames
	private int _pageFaults;		// Page fault count
}
